﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using ThuPhap.ExtensionClass;
using ThuPhap.Class;
using System.ComponentModel;
using ThuPhap.Controls;
using Microsoft.Phone.Tasks;
using System.IO;
using System.Windows.Media.Imaging;
using ThuPhap.Models;
using System.IO.IsolatedStorage;
using System.Windows.Controls.Primitives;
using ThuPhap.ViewModels;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
namespace ThuPhap
{
    public partial class MainPage : PhoneApplicationPage
    {
        private TextControl CurrentTextControl = null;
        public static WriteableBitmap ImageStream = null;
        public static StoredItem StoragePicture;
        private bool flag = false;
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            WriteableBitmap wb = new WriteableBitmap(0, 0).FromResource("Resources/Backgrounds/EmptyBackground.jpg");
            this.BackgroundImage.ImageSource = wb;
            FontPage.FinishedSelectedFontEvent += new FontPage.FinishSelectedDelegate(FontPage_FinishedSelectedFontEvent);
            InputMessageBoxControl.FinishedInputNameEvent += new InputMessageBoxControl.FinishedInputNameDelegate(InputMessageBoxControl_FinishedInputNameEvent);
            ChooseColorPage.FinishChooseBrushEvent += new ChooseColorPage.FinishChooseBrushDelegate(ChooseColorPage_FinishChooseBrushEvent);
            //ChooseImage.FinishChooseImageEvent += new ChooseImage.FinishChooseImageDelegate(ChooseImage_FinishChooseImageEvent);
            SelectBackground.FinishedChooseBackgroundEvent += new SelectBackground.FinishedChooseBackground(SelectBackground_FinishedChooseBackgroundEvent);
            MainCanvas.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(MainCanvas_Tap);
            flag = false;
            if (ImageStream != null)
            {
                this.BackgroundImage.ImageSource = ImageStream;
                ImageStream = null;
            }
        }

        bool times = false;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            
            string type=string.Empty, filename, iscamera,param;
            if (NavigationContext.QueryString.TryGetValue("iscamera", out iscamera))
            {
                if (!times)
                {
                    NavigationService.RemoveBackEntry();
                    times = true;
                }
            }
            if (!flag)
            {
                if (NavigationContext.QueryString.TryGetValue("type", out type) && NavigationContext.QueryString.TryGetValue("filename", out filename))
                {
                    var sp = new SavePictureInfo();
                    var data = sp.GetDataFile(filename);
                    WriteableBitmap wb = new WriteableBitmap((int)data.BackgroundWidth, (int)data.BackgroundHeight).FromByteArray(data.Background);
                    this.BackgroundImage.ImageSource = wb;
                    this.addTextControlToCanvas(data.TextControl);
                    flag = true;
                }
                else if (NavigationContext.QueryString.TryGetValue("type", out type) && NavigationContext.QueryString.TryGetValue("index", out param))
                {
                    int index = int.Parse(param);
                    int tempIndex = 0;
                    var data = App.StartPageViewModel.OnlineTemplates[index];
                    bool isExisted = false;
                    foreach (var iter in App.StartPageViewModel.TemplateItems)
                    {
                        if (data.ID == iter.ID && iter.ID > 0)
                           isExisted = true;

                        if (isExisted) break;
                        else
                            tempIndex++;
                    }

                    if (isExisted)
                    {
                        var template = App.TemplateStored[tempIndex];
                        var ms = new MemoryStream(template.Background);
                        var bmi = new BitmapImage();
                        bmi.SetSource(ms);

                        this.BackgroundImage.ImageSource = new WriteableBitmap(bmi);
                        this.addTextControlToCanvas(template.TextControl);
                        flag = true;
                    }
                    else
                    {
                        try
                        {
                            //download template
                            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Template));
                            var service = new CalligraphyService.IcalligraphyClient();
                            var templateManager = new SaveTemplateInfo();

                            service.GetOnlineTemplateCompleted += (o, ev) =>
                            {

                                Stream stream = new MemoryStream(ev.Result);
                                //save data
                                var temp = xmlSerializer.Deserialize(stream) as Template;
                                templateManager.SavedNewTemplate(temp);
                                App.TemplateStored.Add(temp);

                                //load data to main page
                                var ms = new MemoryStream(temp.Background);
                                var bmi = new BitmapImage();
                                bmi.SetSource(ms);
                                this.BackgroundImage.ImageSource = new WriteableBitmap(bmi);
                                this.addTextControlToCanvas(temp.TextControl);
                                flag = true;

                            };
                            service.GetOnlineTemplateAsync(data.ID);

                        }
                        catch (Exception)
                        {
                           App.StartPageViewModel.IsConnected = false;                            
                        }
                    }
                }
                else if (NavigationContext.QueryString.TryGetValue("index", out param))
                {
                    int index = int.Parse(param);
                    var data = App.TemplateStored[index];
                    var ms = new MemoryStream(data.Background);
                    var bmi = new BitmapImage();
                    bmi.SetSource(ms);

                    this.BackgroundImage.ImageSource = new WriteableBitmap(bmi);
                    this.addTextControlToCanvas(data.TextControl);
                    flag = true;
                }
                
            }
        }

        private void addTextControlToCanvas(ObservableCollection<TextControlInfo> textControls)
        {
            if (textControls.Count != 0)
            {
                foreach (var item in textControls)
                {
                    TextControl textControl = new TextControl();
                    textControl.IsBold = item.IsBold;
                    textControl.IsItalic = item.IsItalic;
                    textControl.Align = item.Align;
                    textControl.Width = item.Width;
                    textControl.Height = item.Height;
                    textControl.FontSize = item.FontSize;
                    textControl.Text = item.Text;
                    var array = item.Foreground.Split('_');
                    textControl.Foreground = new SolidColorBrush(Color.FromArgb(byte.Parse(array[0]), byte.Parse(array[1]), byte.Parse(array[2]), byte.Parse(array[3])));
                    textControl.FontFamily = new FontFamily(item.FontFamily);
                    textControl.IsSelected = false;
                    string unicode;
                    if (item.Type == 2)
                    {
                        unicode = App.ConvertVNCode.VniToUnicode(item.UnicodeText);
                    }
                    else if (item.Type == 1)
                    {
                        unicode = App.ConvertVNCode.TelexToUnicode(item.UnicodeText);
                    }
                    else
                    {
                        unicode = item.UnicodeText;
                    }

                    if (this.TypeInputListPicker.SelectedIndex == 2)
                    {
                        textControl.UnicodeText = App.ConvertVNCode.VniToUnicode(unicode);
                    }
                    else if (this.TypeInputListPicker.SelectedIndex == 1)
                    {
                        textControl.UnicodeText = App.ConvertVNCode.UnicodeToTelex(unicode);
                    }
                    else
                    {
                        textControl.UnicodeText = unicode;
                    }
                    
                    Canvas.SetLeft(textControl, item.Left);
                    Canvas.SetTop(textControl, item.Top);
                    textControl.DragDeltaGestureEvent += new TextControl.DragDeltaGestureDelegate(textControl_DragDeltaGestureEvent);
                    textControl.DoubleTap += new EventHandler<System.Windows.Input.GestureEventArgs>(textControl_DoubleTap);
                    MainCanvas.Children.Add(textControl);
                }
            }
        }

        void MainCanvas_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (this.CurrentTextControl!=null)
            {
               // this.CurrentTextControl.IsSelected = false;
            }
        }

        

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        //Value of index
        //0: EN => English
        //1: Vni => Vni type of Vietnamese
        //2: Telex => Telex type of Vietnamese

        private void ContentTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            //string content = this.ContentTextBox.Text;
            //if (content != string.Empty)
            //{
            //    int index = TypeInputListPicker.SelectedIndex;
            //    if (index == 2)
            //    {
            //        string VniText = App.ConvertVNCode.UnicodeToVni(content);
            //        this.ContentTextBox.Text = App.ConvertVNCode.VniToUnicode(VniText);
            //    }
            //    else if (index == 1)
            //    {
            //        string VniText = App.ConvertVNCode.UnicodeToTelex(content);
            //        this.ContentTextBox.Text = App.ConvertVNCode.TelexToUnicode(VniText);
            //    }

                
            //    //this.ScrollTextBlock.ScrollToVerticalOffset(this.ScrollTextBlock.ScrollableHeight);
            //    //this.ScrollTextBlock.UpdateLayout();
            //}
        }

        private void ContentTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            //this.ContentTextBox.Focus();
            //this.ContentTextBox.SelectionStart = this.ContentTextBox.Text.Length;
        }

        private void UnSelectedChildren()
        {
            foreach (var element in MainCanvas.Children)
            {
                if (element is TextControl)
                {
                    var textControl = element as TextControl;
                    textControl.IsSelected = false;

                }
            }
        }

        //private void Export_Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        //{
        //    try
        //    {
        //        this.UnSelectedChildren();
                
        //        BackgroundWorker exportBackgroundWorker = new BackgroundWorker();
        //        App.LoadingPopup.IsOpen = true;
        //        ExportImage export = new ExportImage();
        //        exportBackgroundWorker.DoWork += ((s, ev) =>
        //        {
                    
        //            //export.Export(MainCanvas);
        //            ev.Result = export.ExportUsingWriteableBitmap(MainCanvas);
                    
        //        });


        //        exportBackgroundWorker.RunWorkerCompleted += ((s, ev) =>
        //        {
        //            //string result = ev.Result as string;
        //            App.LoadingPopup.IsOpen = false;
        //            //string filename = export.saveAsJPGToIsolated();
        //            //export.saveToSavedImagePhone();

        //            string filename = export.SaveToSavedImagePhone(ev.Result.ToString());
        //            MessageBox.Show("Exported image successfully!", "Notice", MessageBoxButton.OK);
                    
        //            //if (result == "1")
        //            //{
        //            //    MessageBox.Show("Exported image successfully!", "Notice", MessageBoxButton.OK);
        //            //}
        //            //else
        //            //{
        //            //    MessageBox.Show(result, "Error", MessageBoxButton.OK);
        //            //}

        //        });

        //        exportBackgroundWorker.RunWorkerAsync();
        //    }
        //    catch (Exception ex)
        //    {
        //        App.LoadingPopup.IsOpen = false;
        //        MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
        //    }
        //    finally
        //    {
        //        //App.LoadingPopup.IsOpen = false;
        //    }
            
        //}

        private void Color_Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //this.IsEnabled = false;
            SolidColorBrush brush = (SolidColorBrush)this.ColorBorder.Background;
            string colorString = string.Format("{0},{1},{2},{3}", brush.Color.A, brush.Color.R,brush.Color.G,brush.Color.B);
            NavigationService.Navigate(new Uri("/ChooseColorPage.xaml?color=" + colorString + "&type=main", UriKind.Relative));
        }


        private void Font_StackPanel_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            
            NavigationService.Navigate(new Uri("/FontPage.xaml?source=" + this.FontFamilyTextBlock.FontFamily.Source.Substring(35).Replace("#","0"), UriKind.Relative));
        }

        void FontPage_FinishedSelectedFontEvent(FontFamily Font)
        {
            //this.IndexFontTextBlock.Text = Index.ToString();
            this.FontFamilyTextBlock.FontFamily = Font;
            var element = this.GetSelectedTextControl();
            if (element != null)
            {
                element.FontFamily = this.FontFamilyTextBlock.FontFamily;
            }
        }

        void ChooseColorPage_FinishChooseBrushEvent(Brush Brush)
        {
            this.ColorBorder.Background = Brush;
            var element = this.GetSelectedTextControl();
            if (element != null)
            {
                element.Foreground = Brush;
            }
        }

        void SelectBackground_FinishedChooseBackgroundEvent(System.Windows.Media.Imaging.WriteableBitmap Bitmap)
        {
            this.BackgroundImage.ImageSource = Bitmap;
        }

        private void Image_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/SelectBackground.xaml", UriKind.Relative));
            //PhotoChooserTask photoChooser = new PhotoChooserTask();
            //photoChooser.ShowCamera = true;
            //photoChooser.Show();
            //photoChooser.Completed += new EventHandler<PhotoResult>(photoChooser_Completed);
        }

        private void GestureListener_DragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            TextControl textControl = sender as TextControl;
            if (textControl.IsSelected == false)
                return;
            var x = Canvas.GetLeft(textControl) + e.HorizontalChange;
            var y = Canvas.GetTop(textControl) + e.VerticalChange;
            var actualCanvasWidth = MainCanvas.Width * 1;
            var actualCanvasHeight = MainCanvas.Height * 1;
            var tempWidth = x + textControl.ActualWidth;
            var tempHeight = y + textControl.ActualHeight;
            double distance = -20;
            if (y <= distance)
            {
                y = distance;
            }

            if (tempHeight > actualCanvasHeight - distance)
            {
                y = actualCanvasHeight - textControl.ActualHeight - distance;
            }

            if (x <= distance)
            {
                x = distance;
            }

            if (tempWidth > actualCanvasWidth - distance)
            {
                x = actualCanvasWidth - textControl.ActualWidth - distance;
            }

            //var newX = (x + textBlock.ActualWidth) >= actualCanvasWidth ? actualCanvasWidth - textBlock.ActualWidth : x;
            // var newY = (y + textBlock.ActualHeight) >= actualCanvasHeight ? actualCanvasHeight - textBlock.ActualHeight : y;

            //text1.Text = string.Format("x={0}:y={1}:w={2}", x, y,textBlock.ActualWidth);
            Canvas.SetLeft(textControl, x);
            Canvas.SetTop(textControl, y);
        }

        private void GestureListener_DragStarted(object sender, DragStartedGestureEventArgs e)
        {
            TextControl textControl = sender as TextControl;
            if (textControl.IsSelected == false)
                return;
            
        }

        private void GestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
        {
            TextControl textControl = sender as TextControl;
            if (textControl.IsSelected == false)
                return;
            
        }

        private TextControl GetSelectedTextControl()
        {
            TextControl textControlElement = null;
            foreach (var element in MainCanvas.Children)
            {
                if (element is TextControl)
                {
                    var textControl = element as TextControl;

                    if (textControl.IsSelected == true)
                    {
                        textControlElement = textControl;
                        break;
                    }
                }
            }

            return textControlElement;
        }

        private void TextBlock_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void TextStackPanel_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            foreach (var element in MainCanvas.Children)
            {
                if (element is TextControl)
                {
                    var textControlElement = element as TextControl;
                    textControlElement.IsSelected = false;
                }
            }

            TextControl textControl = new TextControl();
            textControl.Width = 300;
            textControl.Height = 100;
            textControl.IsSelected = true;
            textControl.FontFamily = this.FontFamilyTextBlock.FontFamily;
            textControl.FontSize = double.Parse(this.FontSizeTextBox.Text) / 0.8;
            textControl.Foreground = this.ColorBorder.Background;
            textControl.IsBold = BoldBorder.Opacity == 0 ? false : true;
            textControl.IsItalic = ItalicBorder.Opacity == 0 ? false : true;
            textControl.Align = AlignListPicker.SelectedIndex;

            //textControl.Style = Resources["DragDropTextControlStyle"] as Style;
            textControl.DragDeltaGestureEvent += new TextControl.DragDeltaGestureDelegate(textControl_DragDeltaGestureEvent);
            textControl.DoubleTap += new EventHandler<System.Windows.Input.GestureEventArgs>(textControl_DoubleTap);
            //textControl.DoubleTapTextControlEvent += new TextControl.abc(textControl_DoubleTapTextControlEvent);
            MainCanvas.Children.Add(textControl);
            this.CurrentTextControl = textControl;
        }

        

        void textControl_DragDeltaGestureEvent(object sender, DragDeltaGestureEventArgs e)
        {
            TextControl textControl = sender as TextControl;
            if (textControl.IsSelected == false)
                return;
            var x = Canvas.GetLeft(textControl) + e.HorizontalChange;
            var y = Canvas.GetTop(textControl) + e.VerticalChange;
            var actualCanvasWidth = MainCanvas.Width * 1;
            var actualCanvasHeight = MainCanvas.Height * 1;
            var tempWidth = x + textControl.ActualWidth;
            var tempHeight = y + textControl.ActualHeight;
            double distance = -30;
            if (y <= distance)
            {
                y = distance;
            }

            if (tempHeight > actualCanvasHeight - distance)
            {
                y = actualCanvasHeight - textControl.ActualHeight - distance;
            }

            if (x <= distance)
            {
                x = distance;
            }

            if (tempWidth > actualCanvasWidth - distance)
            {
                x = actualCanvasWidth - textControl.ActualWidth - distance;
            }

            //var newX = (x + textBlock.ActualWidth) >= actualCanvasWidth ? actualCanvasWidth - textBlock.ActualWidth : x;
            // var newY = (y + textBlock.ActualHeight) >= actualCanvasHeight ? actualCanvasHeight - textBlock.ActualHeight : y;

            //text1.Text = string.Format("x={0}:y={1}:w={2}", x, y,textBlock.ActualWidth);
            Canvas.SetLeft(textControl, x);
            Canvas.SetTop(textControl, y);
        }
        void textControl_DoubleTapTextControlEvent(object sender, System.Windows.Input.GestureEventArgs e)
        {
            TextControl textControl = sender as TextControl;
            foreach (var element in MainCanvas.Children)
            {
                if (element is TextControl)
                {
                    var textControlElement = element as TextControl;
                    if (textControl == textControlElement)
                    {
                        textControl.IsSelected = false;
                        break;
                    }
                }
            }
        }

        void textControl_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var textControl = sender as TextControl;
            foreach (var element in MainCanvas.Children)
            {
                if (element is TextControl)
                {
                    var textControlElement = element as TextControl;
                    if (textControl == textControlElement)
                    {
                        
                        textControl.IsSelected = !textControl.IsSelected;
                        //textControl.IsSelected = true;
                        if (textControl.IsSelected)
                            this.CurrentTextControl = textControl;
                        else
                            this.CurrentTextControl = null;
                        this.UpdateValueBinding(textControl);
                    }
                    else
                    {
                        textControlElement.IsSelected = false;
                    }
                }
            }

        }

        private void UpdateValueBinding(TextControl textControl)
        {
            this.FontSizeTextBox.Text = (Math.Round(textControl.FontSize * 0.8)).ToString();
            this.ColorBorder.Background = textControl.Foreground;
            this.FontFamilyTextBlock.FontFamily = textControl.FontFamily;
            this.AlignListPicker.SelectedIndex = textControl.Align;
            this.BoldBorder.Opacity = textControl.IsBold == true ? 0.3 : 0;
            this.ItalicBorder.Opacity = textControl.IsItalic == true ? 0.3 : 0;
        }

        private void TypeInputListPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var listPicker = sender as ListPicker;
            if (listPicker!=null)
            {
                App.Typing = listPicker.SelectedIndex;    
            }
            
        }

        private void FontSizeTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                double value = double.Parse(FontSizeTextBox.Text);
                var element = this.GetSelectedTextControl();
                if (element != null)
                {
                    element.FontSize = value / 0.8;
                }
            }
            catch { }
        }

        private void RemoveStackPanel_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var element = this.GetSelectedTextControl();
            if (element != null)
            {
                MainCanvas.Children.Remove(element);
            }
        }

        private void StackPanel_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void AlignListPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                int value = this.AlignListPicker.SelectedIndex;
                var element = this.GetSelectedTextControl();
                if (element != null)
                {
                    element.Align = value;
                }
            }
            catch { }
        }

        private void BoldStackPanel_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                this.BoldBorder.Opacity = this.BoldBorder.Opacity == 0 ? 0.3 : 0;
                var element = this.GetSelectedTextControl();
                if (element != null)
                {
                    element.IsBold = this.BoldBorder.Opacity == 0 ? false : true;
                }
            }
            catch { }
        }

        private void ItalicStackPanel_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            try
            {
                this.ItalicBorder.Opacity = this.ItalicBorder.Opacity == 0 ? 0.3 : 0;
                var element = this.GetSelectedTextControl();
                if (element != null)
                {
                    element.IsItalic = this.ItalicBorder.Opacity == 0 ? false : true;
                }
            }
            catch { }
        }
        WriteableBitmap writeableBitmap;
        private void ExportApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            string captain = "Notice";
            string message = "Do you want to export image?";
            string question = "Save exported image to your pictures";
            string type = "main";
            this.UnSelectedChildren();
            Transform tranform = MainCanvas.TransformToVisual(MainCanvas) as Transform;
            writeableBitmap = new System.Windows.Media.Imaging.WriteableBitmap(MainCanvas, tranform);
            NavigationService.Navigate(new Uri(string.Format("/MessageBoxControl.xaml?type={3}&captain={0}&message={1}&question={1}", captain, message, question, type), UriKind.Relative));
            MessageBoxControl.OKEventMain += new MessageBoxControl.OKDelegate(MessageBoxControl_OKEventMain);

            #region old region
            /*
            var result = MessageBox.Show("Do you want to export image?", "Notice", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                try
                {
                    this.UnSelectedChildren();

                    BackgroundWorker exportBackgroundWorker = new BackgroundWorker();
                    App.LoadingPopup.IsOpen = true;
                    Transform tranform = MainCanvas.TransformToVisual(MainCanvas) as Transform;
                    var writeableBitmap = new System.Windows.Media.Imaging.WriteableBitmap(MainCanvas, tranform);
                    ExportImage export = new ExportImage();

                    //try
                    //{
                    //    string filenameIsolatedStorage = export.ExportUsingWriteableBitmap(MainCanvas);
                    //    string filenameGalleryPhone = export.SaveToSavedImagePhone(filenameIsolatedStorage);
                    //    MessageBox.Show("Exported image successfully!", "Notice", MessageBoxButton.OK);
                    //}
                    //catch (Exception ex)
                    //{
                    //    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
                    //}

                    exportBackgroundWorker.DoWork += ((s, ev) =>
                    {

                        ev.Result = export.ExportUsingWriteableBitmap(writeableBitmap);

                    });


                    exportBackgroundWorker.RunWorkerCompleted += ((s, ev) =>
                    {
                        //string result = ev.Result as string;

                        string filename = ev.Result as string;
                        //export.SaveToSavedImagePhone(filename);
                        SaveGalleryData saveGallery = new SaveGalleryData();
                        saveGallery.AddGalleryItem(new Models.GalleryItem() { Name = filename, Date = DateTime.Now, Image = filename });
                        App.LoadingPopup.IsOpen = false;
                        MessageBox.Show("Exported image successfully!", "Notice", MessageBoxButton.OK);

                    //    //if (result == "1")
                    //    //{
                    //    //    MessageBox.Show("Exported image successfully!", "Notice", MessageBoxButton.OK);
                    //    //}
                    //    //else
                    //    //{
                    //    //    MessageBox.Show(result, "Error", MessageBoxButton.OK);
                    //    //}

                    });

                    exportBackgroundWorker.RunWorkerAsync();
                }
                catch (Exception ex)
                {
                    App.LoadingPopup.IsOpen = false;
                    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
                }
                finally
                {
                    //App.LoadingPopup.IsOpen = false;
                }
            }
             */
            #endregion
        }

        void MessageBoxControl_OKEventMain(bool IsGallery)
        {
            try
            {
                

                BackgroundWorker exportBackgroundWorker = new BackgroundWorker();
                App.LoadingPopup.IsOpen = true;

                ExportImage export = new ExportImage();
                //try
                //{
                //    string filenameIsolatedStorage = export.ExportUsingWriteableBitmap(MainCanvas);
                //    string filenameGalleryPhone = export.SaveToSavedImagePhone(filenameIsolatedStorage);
                //    MessageBox.Show("Exported image successfully!", "Notice", MessageBoxButton.OK);
                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
                //}

                exportBackgroundWorker.DoWork += ((s, ev) =>
                {
                    ev.Result = export.ExportUsingWriteableBitmap(writeableBitmap);

                });


                exportBackgroundWorker.RunWorkerCompleted += ((s, ev) =>
                {
                    string filename = ev.Result as string;

                    //string filename = export.SaveAsJPGToIsolated();
                    //export.SaveToSavedImagePhone(filename);
                    SaveGalleryData saveGallery = new SaveGalleryData();
                    var gallery = new Models.GalleryItem() { Name = filename, Date = DateTime.Now, Image = filename };
                    saveGallery.AddGalleryItem(gallery);
                    App.LoadingPopup.IsOpen = false;
                    if (IsGallery)
                    {
                        export.SaveToSavedImagePhone(filename);
                    }
                    
                    //Add item in gallery
                    Deployment.Current.Dispatcher.BeginInvoke(new AddItemToGalleryDelegate(AddItemToGallery), gallery);

                    MessageBox.Show("Exported image successfully!", "Notice", MessageBoxButton.OK);
                    //NavigationService.Navigate(new Uri("/MessageBox.xaml", UriKind.Relative));

                    //    //if (result == "1")
                    //    //{
                    //    //    MessageBox.Show("Exported image successfully!", "Notice", MessageBoxButton.OK);
                    //    //}
                    //    //else
                    //    //{
                    //    //    MessageBox.Show(result, "Error", MessageBoxButton.OK);
                    //    //}

                });

                exportBackgroundWorker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                App.LoadingPopup.IsOpen = false;
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK);
            }
            finally
            {
                //App.LoadingPopup.IsOpen = false;
            }
            MessageBoxControl.OKEventMain -= new MessageBoxControl.OKDelegate(MessageBoxControl_OKEventMain);
        }

        private delegate void AddItemToGalleryDelegate(GalleryItem Item);
        private void AddItemToGallery(GalleryItem Item)
        {
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(Item.Image, FileMode.Open, FileAccess.Read))
                {
                    WriteableBitmap writeableBitmap = new WriteableBitmap(0, 0).FromStream(fileStream);
                    var result = writeableBitmap.Crop(0, (writeableBitmap.PixelHeight - writeableBitmap.PixelWidth) / 2, writeableBitmap.PixelWidth, writeableBitmap.PixelWidth);
                    fileStream.Close();
                    Item.Bitmap = result;
                }
            }
            App.StartPageViewModel.GalleryItems.Insert(0, Item);
        }

        private void PreviewApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            this.UnSelectedChildren();
            Transform tranform = MainCanvas.TransformToVisual(MainCanvas) as Transform;
            PreviewPage.writeableBitmap = new System.Windows.Media.Imaging.WriteableBitmap(MainCanvas,tranform);
            NavigationService.Navigate(new Uri("/PreviewPage.xaml", UriKind.Relative));
        }

        Popup popup;
        private void SaveApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            this.UnSelectedChildren();
            //InputMessageBoxControl.FinishedInputNameEvent += new InputMessageBoxControl.FinishedInputNameDelegate(InputMessageBoxControl_FinishedInputNameEvent);
            
            StoragePicture = new StoredItem();
            WriteableBitmap wb = this.BackgroundImage.ImageSource as WriteableBitmap;
            Transform tranform = MainCanvas.TransformToVisual(MainCanvas) as Transform;
            var writeableBitmap = new System.Windows.Media.Imaging.WriteableBitmap(MainCanvas, tranform);
            StoragePicture.Image = writeableBitmap.ToByteArray();
            StoragePicture.Background = wb.ToByteArray();
            StoragePicture.Date = DateTime.Now;
            StoragePicture.BackgroundWidth = wb.PixelWidth;
            StoragePicture.BackgroundHeight = wb.PixelHeight;
            
            foreach (var item in MainCanvas.Children)
            {
                var textControl = item as TextControl;
                GeneralTransform gt = textControl.TransformToVisual(MainCanvas);
                Point point = gt.Transform(new Point(0,0));
                var color = (SolidColorBrush)textControl.Foreground;
                var font = textControl.FontFamily.Source;
                
                StoragePicture.TextControl.Add(new TextControlInfo()
                {
                    Align = textControl.Align,
                    FontFamily = font,
                    FontSize = textControl.FontSize,
                    IsBold = textControl.IsBold,
                    IsItalic = textControl.IsItalic,
                    IsSelected = false,
                    Text = textControl.Text,
                    Foreground = (string.Format("{0}_{1}_{2}_{3}",color.Color.A,color.Color.R, color.Color.G, color.Color.B)),
                    Width = textControl.Width,
                    Height = textControl.Height,
                    Left = point.X,
                    Top = point.Y,
                    Type = this.TypeInputListPicker.SelectedIndex,
                    UnicodeText = textControl.UnicodeText
                }
                );

            }
            
            NavigationService.Navigate(new Uri("/InputMessageBoxControl.xaml", UriKind.Relative));
        }

        BackgroundWorker backgroundSave;
        void InputMessageBoxControl_FinishedInputNameEvent(string FileName, bool IsReplace = false)
        {
            popup = new Popup() { Child = new LoadingControl("Saving ..."), IsOpen = true };
            StoragePicture.Name = FileName.Replace(' ','_');
            SavePictureInfo savePicture = new SavePictureInfo();
            backgroundSave = new BackgroundWorker();
            backgroundSave.DoWork += ((s, ev) =>
            {
                savePicture.SavedNewPiture(StoragePicture);
            });
            backgroundSave.RunWorkerCompleted += ((s, ev) =>
            {
                popup.IsOpen = false;
            });
            if (IsReplace)
            {
                Deployment.Current.Dispatcher.BeginInvoke(new RemovedItemStorageDelegate(RemovedItemStorage), FileName);
            }
            Deployment.Current.Dispatcher.BeginInvoke(new AddItemToStoredItemDelegate(AddItemToStoredItem), StoragePicture);
            backgroundSave.RunWorkerAsync();
            //InputMessageBoxControl.FinishedInputNameEvent -= new InputMessageBoxControl.FinishedInputNameDelegate(InputMessageBoxControl_FinishedInputNameEvent);
            
        }

        private delegate void RemovedItemStorageDelegate(string FileName);
        private void RemovedItemStorage(string FileName)
        {
            var item = App.StartPageViewModel.StoredItems.Single(o => o.Name == FileName + ".tp");
            App.StartPageViewModel.StoredItems.Remove(item);
        }

        private delegate void AddItemToStoredItemDelegate(StoredItem StoredItem);
        private void AddItemToStoredItem(StoredItem StoredItem)
        {
            WriteableBitmap writeableBitmap = new WriteableBitmap(480, 800).FromByteArray(StoredItem.Image);
            writeableBitmap = writeableBitmap.Crop(0, (writeableBitmap.PixelHeight - writeableBitmap.PixelWidth) / 2, writeableBitmap.PixelWidth, writeableBitmap.PixelWidth);
            FileViewModel file = new FileViewModel()
            {
                Name = StoredItem.Name + ".tp",
                Date = StoredItem.Date,
                Image = writeableBitmap
            };
            App.StartPageViewModel.StoredItems.Insert(0, file);
        }
        
        //void photoChooser_Completed(object sender, PhotoResult e)
        //{
        //    Deployment.Current.Dispatcher.BeginInvoke(() =>
        //    {
        //        if (e.ChosenPhoto != null)
        //        {
        //            ChooseImage.PhotoStream = e.ChosenPhoto;
        //            NavigationService.Navigate(new Uri("/ChooseImage.xaml", UriKind.Relative));
        //        }
        //    });
        //}

        //void ChooseImage_FinishChooseImageEvent(System.Windows.Media.Imaging.BitmapSource Image)
        //{
        //    this.BackgroundImage.ImageSource = Image;
        //}


        public BackgroundWorker background { get; set; }
    }
}